<?php
if (!function_exists('good_stock')) {

	/**
	 * 检查商品库存
	 * @param  int  $spId  商品规格ID
	 * @param  boolean|int $pay_amount 要购买的数量
	 * @param  int $gId 商品ID
	 * @return 
	 */
	function good_stock($spId=0, $pay_amount, $gId=0)
	{
		

		$amount = \app\api\model\Good::where('id', $gId)->value('stock');
		
		
  
		return $pay_amount ? $pay_amount <= $amount : $amount;
	}
}


if (!function_exists('good_xj_status')) {

	/**
	 * 检查商品上下架状态 
	 * @param  [type] $gId  [description]
	 * @param  [type] $spId [description]
	 * @return [type]       [description]
	 */
	function good_xj_status($spId=0, $gId=0)
	{
		

		$is_xj = \app\api\model\Good::where('id', $gId)->value('is_xj');
		
		

		return $is_xj;
	}
}


if (!function_exists('good_status')) {

	/**
	 * 检查商品状态 
	 * @param  [type] $gId  [description]
	 * @param  [type] $spId [description]
	 * @return [type]       [description]
	 */
	function good_status($spId=0, $pay_amount ,$gId=0)
	{

		return	good_stock($spId, $pay_amount, $gId) || good_xj_status($spId, $gId);
		
	}
}

if (!function_exists('get_wechat_config')) {
	
	function get_wechat_config($sid){

		$storeinfo = \app\api\model\YupShop::get($sid);

		// 微信 配置
    	$data =  [
	        'token'          => 'yuptec20200902',
	        'appid'          => $storeinfo['appid'],
	        'appsecret'      => $storeinfo['secret'],
	        'encodingaeskey' => 'FE53IPpMbqIdcI9jdrHpFvW0OcxkwSXn2qpKduxBa8P',
	        // 配置商户支付参数（可选，在使用支付功能时需要）
	        'mch_id'         => $storeinfo['mch_id'],
	        'mch_key'        => $storeinfo['key'],
	        // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
	        'ssl_key'        => '',
	        'ssl_cer'        => '',
	        // 缓存目录配置（可选，需拥有读写权限）
	        'cache_path'     => dirname(__DIR__).'/runtime/cache',
	    ];

	    return $data;
	}
}


if (!function_exists('template_send_order')) {
    
    function template_send_order($touser, $redirectUrl, $order_sn, $price, $config, $remark='感谢您的支持，我们将尽快发货！', $first='您好，感谢使用百年红！')
    {
        $templateModel = new \WeChat\Template($config);
        $templateData = [
            'touser' => $touser,
            'template_id' => 'O9qtxsOSbfzr8TjuWtaNo8mrPrPrA10lOJaTF7dhCM8',
            'url'   => $redirectUrl,
            'topcolor' => '#FF0000',
            'data'  => [
                'first'=>[
                    'value'=>$first
                ], 
                'orderno'=>[
                    'value'=>$order_sn
                ], 
                'amount'=>[
                    'value'=>sprintf('%.2f', $price).'元'
                ], 
                'remark'=>[
                    'value'=>$remark
                ]
            ]
        ];

        $templateModel->send($templateData);
    }
}




//下单通知所有管理员
if (!function_exists('template_create_order')) {
    
    function template_create_order($touser, $order_sn, $time, $name, $phone, $address, $config)
    {	
    	$remark='请登录后端核实订单并及时发货！';
    	$first='您好，收到一份新订单，请及时查看！';

        $templateModel = new \WeChat\Template($config);
        $templateData = [
            'touser' => $touser,
            'template_id' => 'phRIcfnGLKrfNltiweyY-nadhPWC0C5JDyMqcmAI3GQ',
            'url'   => '',
            'topcolor' => '#FF0000',
            'data'  => [
                'first'=>[
                    'value'=>$first
                ], 
                'keyword1'=>[
                    'value'=>$order_sn
                ], 
                'keyword2'=>[
                    'value'=>$time
                ],
                'keyword3'=>[
                    'value'=>$name
                ],
                'keyword4'=>[
                    'value'=>$phone
                ], 
                'keyword5'=>[
                    'value'=>$address
                ], 
                'remark'=>[
                    'value'=>$remark
                ]
            ]
        ];

        $templateModel->send($templateData);
    }
}




if (!function_exists('template_pay_order')) {
    
    function template_pay_order($touser, $redirectUrl, $order_sn, $price, $config, $remark='感谢您的支持，我们将尽快发货！', $first='您好，感谢使用百年红！')
    {
        $templateModel = new \WeChat\Template($config);
        $templateData = [
            'touser' => $touser,
            'template_id' => 'O9qtxsOSbfzr8TjuWtaNo8mrPrPrA10lOJaTF7dhCM8',
            'url'   => $redirectUrl,
            'topcolor' => '#FF0000',
            'data'  => [
                'first'=>[
                    'value'=>$first
                ], 
                'orderno'=>[
                    'value'=>$order_sn
                ], 
                'amount'=>[
                    'value'=>sprintf('%.2f', $price).'元'
                ], 
                'remark'=>[
                    'value'=>$remark
                ]
            ]
        ];
        $templateModel->send($templateData);
    }
}

if (!function_exists('captcha')) {
    /**
     * 
     * @param  integer  $phone    [手机号]
     * @param  integer $category [description]
     * @param  integer  $uId      []
     * @return [type]            [description]
     */
    function captcha($phone, $category=0, $uId=null, $type=0)
    {
        
        $client = new \JiGuang\JSMS(config('jg.appkey'), config('jg.appsecret'), [ 'disable_ssl' => true ]);
        
        //14597
        if($type){
            $response = $client->sendCode($phone, 1, 8858);
        }else{
            $response = $client->sendCode($phone, 1, 8858);
        }
        
        // halt($response);
        if (!empty($response['body']['msg_id'])) {
            // 记录
            $record = ['msg_id'=>$response['body']['msg_id'], 'phone'=>$phone, 'category'=>$category];
            if ($uId !== null) {
                $record['uId'] = $uId;
            }
            \app\api\model\YupSmsLog::create($record);

            return true;
        }else{
            // 发送失败
            return false;
        }
    }
}


if (!function_exists('check_captcha')) {

	function check_captcha($phone, $code, $uId, $category=0)
	{
		// 验证码核对 
		if (!empty($phone) && !empty($code)) {
			$msg_id = \app\api\model\YupSmsLog::where(['uId'=>$uId, 'category'=>$category, 'phone'=>$phone])->order('create_time desc')->value('msg_id');

			
			if (empty($code) || empty($msg_id)) {
				return false;
			}
			$client = new \JiGuang\JSMS(config('jg.appkey'), config('jg.appsecret'), [ 'disable_ssl' => true ]);
			$response = $client->checkCode($msg_id, $code);

			if (!isset($response['body']['is_valid'])) {
				return false;
			}
			if ($response['body']['is_valid'] !== true) {
				//$response['body']['error']['message']
				return false;
			}
			return true;
		}
	}
}



if (!function_exists('sms_notice')) {

    function sms_notice($phone,$msg_id,$time,$sign_id,$storename,$type,$code)
    {
            
            
            $client = new \JiGuang\JSMS(config('jg.appkey'), config('jg.appsecret'), [ 'disable_ssl' => true ]);
            $aaa = $client->sendMessage1($phone,$msg_id,$time,$sign_id,$storename,$type,$code);
           
    }
}